const cluster = require('cluster');
const os = require('os');
const cpuNum = os.cpus().length;

if(cluster.isMaster) {
	for (let i = 0; i < cpuNum - 1; i++) {
		createWorker();
	}
} else {
	console.log('===>', 'cluster');
	process.on('message', msg => {
		console.log()
		if(msg === 'ping-' + process.pid) {
			process.send('pang-' + process.pid);
		}
	})
	require('./app');
}


function createWorker() {
	const worker = cluster.fork();
	
	let miss = 0;
	
	let timer = setInterval(() => {
		if(miss >= 3) {
			console.log('杀掉僵尸进程' + worker.process.pid)
			clearInterval(timer);
			process.kill(worker.process.pid);
			setTimeout(() => {
				createWorker();
			}, 500);
			return
		}
		miss++;
		console.log('ping-' + worker.process.pid);
		worker.send('ping-' + worker.process.pid);
	}, 1000);
	
	worker.on('message', msg => {
		if(msg === 'pang-' + worker.process.pid) {
			console.log('pang')
			miss--;
		}
	});
	worker.on('exit', function () {
		clearInterval(timer);
	});
}
